<?php

// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.


/**
 * Table Library
 *
 * @package   blocks-email_list
 * @author    Toni Mas <toni.mas@uib.dot.es>
 * @copyright 2006 by <toni.mas at uib dot es>
 * @license   The source code packaged with this file is Free Software, Copyright (C) 2009 by
 *            <toni.mas at uib dot es>.
 *          It's licensed under the AFFERO GENERAL PUBLIC LICENSE unless stated otherwise.
 *          You can get copies of the licenses here:
 *                         http://www.affero.org/oagpl.html
 *          AFFERO GENERAL PUBLIC LICENSE is also included in the file called "COPYING".
 */

if (! defined('TABLE_VAR_SORT')) {
    define('TABLE_VAR_SORT',   1);
    define('TABLE_VAR_HIDE',   2);
    define('TABLE_VAR_SHOW',   3);
    define('TABLE_VAR_IFIRST', 4);
    define('TABLE_VAR_ILAST',  5);
    define('TABLE_VAR_PAGE',   6);
}

/**
 * Email Flexible Table
 *
 * @copyright 2006 by <toni.mas at uib dot es>
 * @license   http://www.affero.org/oagpl.html AFFERO GENERAL PUBLIC LICENSE
 */
class email_flexible_table {

    protected $uniqueid        = null;
    protected $attributes      = array();
    protected $headers         = array();
    protected $columns         = array();
    protected $column_style    = array();
    protected $column_class    = array();
    protected $column_suppress = array();
    protected $setup           = false;
    protected $sess            = null;
    protected $baseurl         = null;
    protected $request         = array();

    protected $is_collapsible = false;
    protected $is_sortable    = false;
    protected $use_pages      = false;
    protected $use_initials   = false;

    protected $maxsortkeys = 2;
    protected $pagesize    = 30;
    protected $currpage    = 0;
    protected $totalrows   = 0;
    protected $sort_default_column = null;
    protected $sort_default_order  = SORT_ASC;

    // Antoni Mas. Add
    protected $input        = false;

    /**
     * Constructor
     *
     * @param Int $uniqueid The uniqued id of the table
     * @return null
     */
    function email_flexible_table($uniqueid) {
        $this->uniqueid = $uniqueid;
        $this->request  = array(
            TABLE_VAR_SORT    => 'tsort',
            TABLE_VAR_HIDE    => 'thide',
            TABLE_VAR_SHOW    => 'tshow',
            TABLE_VAR_IFIRST  => 'tifirst',
            TABLE_VAR_ILAST   => 'tilast',
            TABLE_VAR_PAGE    => 'page'
        );
    }

    /**
     * Set whether the table is sortable and how
     *
     * @param boolean $bool          Whether it's sortable
     * @param string  $defaultcolumn Default column to sort by
     * @param string  $defaultorder  Default order ot sort in
     * @return null
     */
    function sortable($bool, $defaultcolumn = null, $defaultorder = SORT_ASC) {
        $this->is_sortable = $bool;
        $this->sort_default_column = $defaultcolumn;
        $this->sort_default_order  = $defaultorder;
    }

    /**
     * Set whether the table is collapsible
     *
     * @param Boolean $bool Whether the table is collapsible
     * @return null
     */
    function collapsible($bool) {
        $this->is_collapsible = $bool;
    }

    /**
     * Set whether the table takes input
     *
     * @param Boolean $bool Whether input is allowed
     * @return null
     */
    function inputs($bool) {
        $this->input = $bool;
    }

    /**
     * Set whether the table is pageable
     *
     * @param Boolean $bool Whether the table is pageable
     * @return null
     */
    function pageable($bool) {
        $this->use_pages = $bool;
    }

    /**
     * Set whether the table has initial bars
     *
     * @param Boolean $bool Whether to use initials
     * @return null
     */
    function initialbars($bool) {
        $this->use_initials = $bool;
    }

    /**
     * Set the table page size
     *
     * @param Int $perpage The number of rows per page
     * @param Int $total   The total number of rows
     * @return null
     */
    function pagesize($perpage, $total) {
        $this->pagesize  = $perpage;
        $this->totalrows = $total;
        $this->use_pages = true;
    }

    /**
     * Set the table's control variables
     *
     * @param array $variables The array of control variables
     * @return null
     */
    function set_control_variables($variables) {

        foreach ($variables as $what => $variable) {

            if (isset($this->request[$what])) {
                $this->request[$what] = $variable;
            }
        }
    }

    /**
     * Set an attribute on the table
     *
     * @param String $attribute The attribute name
     * @param String $value     The value
     * @return null
     */
    function set_attribute($attribute, $value) {
        $this->attributes[$attribute] = $value;
    }

    /**
     * Suppress a column
     *
     * @param String $column The column name
     * @return null
     */
    function column_suppress($column) {

        if (isset($this->column_suppress[$column])) {
            $this->column_suppress[$column] = true;
        }
    }

    /**
     * Set a class on a column
     *
     * @param String $column    The column name
     * @param String $classname The name of the class
     * @return null
     */
    function column_class($column, $classname) {

        if (isset($this->column_class[$column])) {
            // This space needed so that classnames don't run together in the HTML
            $this->column_class[$column] = ' '.$classname;
        }
    }

    /**
     * Set a style property on a column
     *
     * @param String $column   The column name
     * @param String $property The property name
     * @param String $value    The value of the property
     * @return null
     */
    function column_style($column, $property, $value) {

        if (isset($this->column_style[$column])) {
            $this->column_style[$column][$property] = $value;
        }
    }

    /**
     * Set a style property on all columns
     *
     * @param String $property The property name
     * @param String $value    The property value
     * @return null;
     */
    function column_style_all($property, $value) {

        foreach (array_keys($this->columns) as $column) {
            $this->column_style[$column][$property] = $value;
        }
    }

    /**
     * Set the baseurl for the table
     *
     * @param string $url The base url for the table
     * @return null
     */
    function define_baseurl($url) {
        $this->reseturl = $url;

        if (!strpos($url, '?')) {
            $this->baseurl = $url.'?';
        } else {
            $this->baseurl = $url.'&amp;';
        }
    }

    /**
     * Define the columns
     *
     * @param array $columns The columns tobe defined
     * @return null
     */
    function define_columns($columns) {
        $this->columns = array();
        $this->column_style = array();
        $this->column_class = array();
        $colnum = 0;

        foreach ($columns as $column) {
            $this->columns[$column]         = $colnum++;
            $this->column_style[$column]    = array();
            $this->column_class[$column]    = '';
            $this->column_suppress[$column] = false;
        }
    }

    /**
     * Define the headers
     *
     * @param array $headers The headers array
     * @return null
     */
    function define_headers($headers) {
        $this->headers = $headers;
    }

    /**
     * Make a styles string
     *
     * @param array &$styles The array of styles
     * @return string The style string
     */
    function make_styles_string(&$styles) {

        if (empty($styles)) {
            return '';
        }

        $string = ' style="';

        foreach ($styles as $property => $value) {
            $string .= $property.':'.$value.';';
        }
        $string .= '"';
        return $string;
    }

    /**
     * Make a string of attributes
     *
     * @param array &$attributes The attributes
     * @return string The attributes string
     */
    function make_attributes_string(&$attributes) {

        if (empty($attributes)) {
            return '';
        }

        $string = ' ';

        foreach ($attributes as $attr => $value) {
            $string .= ($attr.'="'.$value.'" ');
        }

        return $string;
    }

    /**
     * Setup
     *
     * @return boolean Returns false on error
     * @uses $SESSION
     */
    function setup() {
        global $SESSION;

        if (empty($this->columns) || empty($this->uniqueid)) {
            return false;
        }

        if (!isset($SESSION->flextable)) {
            $SESSION->flextable = array();
        }

        if (!isset($SESSION->flextable[$this->uniqueid])) {
            $SESSION->flextable[$this->uniqueid] = new stdClass;
            $SESSION->flextable[$this->uniqueid]->uniqueid = $this->uniqueid;
            $SESSION->flextable[$this->uniqueid]->collapse = array();
            $SESSION->flextable[$this->uniqueid]->sortby   = array();
            $SESSION->flextable[$this->uniqueid]->i_first  = '';
            $SESSION->flextable[$this->uniqueid]->i_last   = '';
        }

        $this->sess = &$SESSION->flextable[$this->uniqueid];

        $varshow   = optional_param($this->request[TABLE_VAR_SHOW], '', PARAM_ALPHANUMEXT);
        $varhide   = optional_param($this->request[TABLE_VAR_HIDE], '', PARAM_ALPHANUMEXT);
        $varsort   = optional_param($this->request[TABLE_VAR_SORT], '', PARAM_ALPHANUMEXT);
        $varilast  = optional_param($this->request[TABLE_VAR_ILAST], '', PARAM_ALPHANUMEXT);
        $varifirst = optional_param($this->request[TABLE_VAR_IFIRST], '', PARAM_ALPHANUMEXT);

        if (!empty($varshow) && isset($this->columns[$varshow])) {
            // Show this column
            $this->sess->collapse[$varshow] = false;

        } else if (!empty($varhide) && isset($this->columns[$varhide])) {
            // Hide this column
            $this->sess->collapse[$varhide] = true;

            if (array_key_exists($varhide, $this->sess->sortby)) {
                unset($this->sess->sortby[$varhide]);
            }
        }

        // Now, update the column attributes for collapsed columns
        foreach (array_keys($this->columns) as $column) {

            if (!empty($this->sess->collapse[$column])) {
                $this->column_style[$column]['width'] = '10px';
            }
        }

        $fullname_sorted = ($varsort == 'firstname' || $varsort == 'lastname') && isset($this->columns['fullname']);

        if (!empty($varsort) && (isset($this->columns[$varsort]) || $fullname_sorted)) {

            if (empty($this->sess->collapse[$varsort])) {

                if (array_key_exists($varsort, $this->sess->sortby)) {
                    // This key already exists somewhere. Change its sortorder and bring it to the top.
                    $sortorder = $this->sess->sortby[$varsort] == SORT_ASC ? SORT_DESC : SORT_ASC;
                    unset($this->sess->sortby[$varsort]);
                    $this->sess->sortby = array_merge(array($varsort => $sortorder), $this->sess->sortby);

                } else {
                    // Key doesn't exist, so just add it to the beginning of the array, ascending order
                    $this->sess->sortby = array_merge(array($varsort => SORT_ASC), $this->sess->sortby);
                }

                // Finally, make sure that no more than $this->maxsortkeys are present into the array
                if (!empty($this->maxsortkeys) && ($sortkeys = count($this->sess->sortby)) > $this->maxsortkeys) {

                    while ($sortkeys-- > $this->maxsortkeys) {
                        array_pop($this->sess->sortby);
                    }
                }
            }
        }


        $is_sorted       = (! empty($this->sess->sortby));
        $default_sorted  = (! empty($this->sort_default_column));
        $sort_col_exists = $default_sorted && (isset($this->columns[$this->sort_default_column]));
        $fullname_sorted = $default_sorted && (in_array('fullname', $this->columns)
                                            && in_array($this->sort_default_column, array('firstname','lastname')));


        // If we didn't sort just now, then use the default sort order if one is defined and the column exists
        if ((! $is_sorted) && ($sort_col_exists || $fullname_sorted)) {
            $default_sort = $this->sort_default_order == SORT_DESC ? SORT_DESC : SORT_ASC;
            $this->sess->sortby = array($this->sort_default_column => $default_sort);
        }


        if (isset($varilast)) {

            if (empty($varilast) || is_numeric(strpos(get_string('alphabet'), $varilast))) {
                $this->sess->i_last = $varilast;
            }
        }

        if (isset($varifirst)) {

            if (empty($varifirst) || is_numeric(strpos(get_string('alphabet'), $varifirst))) {
                $this->sess->i_first = $varifirst;
            }
        }

        if (empty($this->baseurl)) {
            $getcopy  = $_GET;
            unset($getcopy[$this->request[TABLE_VAR_SHOW]]);
            unset($getcopy[$this->request[TABLE_VAR_HIDE]]);
            unset($getcopy[$this->request[TABLE_VAR_SORT]]);
            unset($getcopy[$this->request[TABLE_VAR_IFIRST]]);
            unset($getcopy[$this->request[TABLE_VAR_ILAST]]);
            unset($getcopy[$this->request[TABLE_VAR_PAGE]]);

            $strippedurl = strip_querystring(qualified_me());

            if (!empty($getcopy)) {
                $first = false;
                $querystring = '';

                foreach ($getcopy as $var => $val) {

                    if (!$first) {
                        $first = true;
                        $querystring .= '?'.$var.'='.$val;

                    } else {
                        $querystring .= '&amp;'.$var.'='.$val;
                    }
                }
                $this->reseturl =  $strippedurl.$querystring;
                $querystring .= '&amp;';

            } else {
                $this->reseturl =  $strippedurl.$querystring;
                $querystring = '?';
            }

            $this->baseurl = strip_querystring(qualified_me()) . $querystring;
        }

        // If it's "the first time" we 've been here, forget the previous initials filters
        if (qualified_me() == $this->reseturl) {
            $this->sess->i_first = '';
            $this->sess->i_last  = '';
        }

        $this->currpage = optional_param($this->request[TABLE_VAR_PAGE], 0, PARAM_INT);
        $this->setup = true;

        /// Always introduce the "flexible" class for the table if not specified
        /// No attributes, add flexible class
        if (empty($this->attributes)) {
            $this->attributes['class'] = 'flexible';

            /// No classes, add flexible class
        } else if (!isset($this->attributes['class'])) {
            $this->attributes['class'] = 'flexible';

            /// No flexible class in passed classes, add flexible class
        } else if (!in_array('flexible', explode(' ', $this->attributes['class']))) {
            $this->attributes['class'] = trim('flexible ' . $this->attributes['class']);
        }

    }

    /**
     * Get the SQL sort order
     *
     * @param int $uniqueid The unique id
     * @return string Sort String
     * @uses $SESSION
     */
    function get_sql_sort($uniqueid = null) {

        if ($uniqueid === null) {
            // "Non-static" function call
            if (!$this->setup) {
                return false;
            }
            $sess = &$this->sess;
        } else {
            // "Static" function call
            global $SESSION;

            if (empty($SESSION->flextable[$uniqueid])) {
                return '';
            }
            $sess = &$SESSION->flextable[$uniqueid];
        }

        if (!empty($sess->sortby)) {
            $sortstring = '';

            foreach ($sess->sortby as $column => $order) {

                if (!empty($sortstring)) {
                    $sortstring .= ', ';
                }
                $sortstring .= $column.($order == SORT_ASC ? ' ASC' : ' DESC');
            }
            return $sortstring;
        }
        return '';
    }

    /**
     * Get the starting point of the page
     *
     * @return int The starting point of the page
     */
    function get_page_start() {

        if (!$this->use_pages) {
            return '';
        }
        return $this->currpage * $this->pagesize;
    }

    /**
     * Get the page size
     *
     * @return int The page size
     */
    function get_page_size() {

        if (!$this->use_pages) {
            return '';
        }
        return $this->pagesize;
    }

    /**
     * Get the SQL where clause
     *
     * @return String The where clause
     * @uses $DB
     */
    function get_sql_where() {
        global $DB;

        if (!isset($this->columns['fullname'])) {
            return '';
        }

        $like = $DB->sql_ilike();

        if (!empty($this->sess->i_first) && !empty($this->sess->i_last)) {
            return 'firstname '.$like.' \''.$this->sess->i_first.'%\' AND lastname '.$like.' \''
                               .$this->sess->i_last.'%\'';

        } else if (!empty($this->sess->i_first)) {
            return 'firstname '.$like.' \''.$this->sess->i_first.'%\'';

        } else if (!empty($this->sess->i_last)) {
            return 'lastname '.$like.' \''.$this->sess->i_last.'%\'';
        }

        return '';
    }

    /**
     * Get the firstname initial
     *
     * @return Array The initials of the firstnames
     */
    function get_initial_first() {

        if (!$this->use_initials) {
            return null;
        }

        return $this->sess->i_first;
    }

    /**
     * Get the lastname initial
     *
     * @return Array The initials of the lastnames
     */
    function get_initial_last() {

        if (!$this->use_initials) {
            return null;
        }

        return $this->sess->i_last;
    }

    /**
     * Print the html representation of the table
     *
     * @deprecated Since Moodle 2.0
     * @return null
     */
    function print_html() {
        debugging('print_html() has been deprecated. Please change your code to use get_html() instead.');

        echo $this->get_html();
    }

    /**
     * Get the html for the table
     *
     * @param boolean $addslashes Whether to add slashes
     * @return String The HTML representing the bar
     * @uses $OUTPUT
     */
    function get_bar($type='first') {
        $property = 'i_'. $type;
        $field = TABLE_VAR_ILAST;

        if ($type == 'first') {
            $field = TABLE_VAR_IFIRST;
        }

        $html = '<div class="initialbar '. $type .'initial">'. get_string($type .'name') .' : ';
        if (!empty($this->sess->$property)) {
            $html .= '<a href="'.$this->baseurl . $this->request[$field].'=">'.$strall.'</a>';
        } else {
            $html .= '<strong>'.$strall.'</strong>';
        }

        foreach ($alpha as $letter) {

            if ($letter == $this->sess->$property) {
                $html .= ' <strong>'.$letter.'</strong>';
            } else {
                $html .= ' <a href="'.$this->baseurl.$this->request[$field].'='
                       .$letter.'">'.$letter.'</a>';
            }
        }
        $html .= '</div>';

        return $html;
    }

    /**
     * Get the html for the table
     *
     * @param boolean $addslashes Whether to add slashes
     * @return String The HTML representing the table
     * @uses $OUTPUT
     */
    function get_html($addslashes=false) {
        global $OUTPUT;

        if (! $this->setup) {
            return false;
        }

        $code = '';

        // Antoni Mas
        if ($this->input) {
            $code = '<script type="text/javascript" language="JavaScript">
                <!--
                        function select_all( field, checked ) {
                            if ( field.length == null) {
                                field.checked = checked;
                            } else {
                                for (var i = 0; i < field.length; i++) {
                                    field[i].checked = checked ;
                                }
                            }
                        }
                    -->
                 </script>';
        }

        $colcount = count($this->columns);

        // Do we need to print initial bars?

        if ($this->use_initials && isset($this->columns['fullname'])) {

            $strall = get_string('all');
            $alpha  = explode(',', get_string('alphabet'));

            // Bar of first initials
            $code .= $this->get_bar('first');

            // Bar of last initials
            $code .= $this->get_bar('last');
        }

        // End of initial bars code

        // Paging bar
        if ($this->use_pages) {
            $pagingbar = new paging_bar($this->totalrows, $this->currpage, $this->pagesize,
                                        $this->baseurl, $this->request[TABLE_VAR_PAGE]);
            $code .= $OUTPUT->render($pagingbar);
        }

        if (empty($this->data)) {
            $code .= $OUTPUT->heading(get_string('nothingtodisplay'));

            if ($addslashes) {
                $code = addslashes($code);
            }
            return $code;
        }


        $suppress_enabled = array_sum($this->column_suppress);
        $suppress_lastrow = null;
        // Start of main data table

        $code .= '<table'.$this->make_attributes_string($this->attributes).'>';

        $code .= '<tr>';

        foreach ($this->columns as $column => $index) {
            $icon_hide = '';
            $icon_sort = '';

            if ($this->is_collapsible) {

                if (!empty($this->sess->collapse[$column])) {
                    // some headers contain < br/> tags, do not include in title
                    $icon_hide = ' <a href="'.$this->baseurl.$this->request[TABLE_VAR_SHOW].'='
                               .$column.'"><img src="'.$OUTPUT->pix_url('t/switch_plus') .'" title="'
                               .get_string('show').' '.strip_tags($this->headers[$index]).'" alt="'
                               .get_string('show').'" /></a>';

                } else if ($this->headers[$index] !== null) {
                    // some headers contain < br/> tags, do not include in title
                    $icon_hide = ' <a href="'.$this->baseurl.$this->request[TABLE_VAR_HIDE].'='
                               .$column.'"><img src="'.$OUTPUT->pix_url('t/switch_minus') .'" title="'
                               .get_string('hide').' '.strip_tags($this->headers[$index]).'" alt="'
                               .get_string('hide').'" /></a>';
                }
            }

            $primary_sort_column = '';
            $primary_sort_order  = '';

            if (reset($this->sess->sortby)) {
                $primary_sort_column = key($this->sess->sortby);
                $primary_sort_order  = current($this->sess->sortby);
            }

            $icon_up   = ' <img src="'. $OUTPUT->pix_url('t/up') .'" alt="'. get_string('desc') .'" />';
            $icon_down = ' <img src="'. $OUTPUT->pix_url('t/down') .'" alt="'. get_string('asc') .'" />';

            switch($column) {

                case 'fullname':

                    if ($this->is_sortable) {
                        $icon_sort_first = $icon_sort_last = '';

                        if ($primary_sort_column == 'firstname') {
                            $lsortorder = get_string('asc');

                            if ($primary_sort_order == SORT_ASC) {
                                $icon_sort_first = $icon_down;
                                $fsortorder = get_string('asc');
                            } else {
                                $icon_sort_first = $icon_up;
                                $fsortorder = get_string('desc');
                            }

                        } else if ($primary_sort_column == 'lastname') {
                            $fsortorder = get_string('asc');

                            if ($primary_sort_order == SORT_ASC) {
                                $icon_sort_last = $icon_down;
                                $lsortorder = get_string('asc');
                            } else {
                                $icon_sort_last = $icon_up;
                                $lsortorder = get_string('desc');
                            }

                        } else {
                            $fsortorder = get_string('asc');
                            $lsortorder = get_string('asc');
                        }
                        $this->headers[$index] = '<a href="'.$this->baseurl.$this->request[TABLE_VAR_SORT]
                                               .        '=firstname">'.get_string('firstname')
                                               .        '<span class="accesshide">'.get_string('sortby')
                                               .        ' '. get_string('firstname') .' '.$fsortorder
                                               .        '</span></a> '. $icon_sort_first .' / '
                                               .'<a href="'.$this->baseurl.$this->request[TABLE_VAR_SORT]
                                               .        '=lastname">'.get_string('lastname')
                                               .        '<span class="accesshide">'.get_string('sortby')
                                               .        ' '.get_string('lastname').' '.$lsortorder
                                               .        '</span></a> '.$icon_sort_last;
                    }
                    break;

                case 'userpic':
                    // do nothing, do not display sortable links
                    break;

                default:

                    if ($this->is_sortable) {

                        if ($primary_sort_column == $column) {

                            if ($primary_sort_order == SORT_ASC) {
                                $icon_sort = $icon_down;
                                $localsortorder = get_string('asc');
                            } else {
                                $icon_sort = $icon_up;
                                $localsortorder = get_string('desc');
                            }
                        } else {
                            $localsortorder = get_string('asc');
                        }
                        $this->headers[$index] = '<a href="'.$this->baseurl.$this->request[TABLE_VAR_SORT]
                                               .        '='.$column.'">'.$this->headers[$index]
                                               .        '<span class="accesshide">'.get_string('sortby')
                                               .        ' '.$this->headers[$index].' '.$localsortorder
                                               .        '</span></a>';
                    }
            }

            if ($this->headers[$index] === null) {
                $code .= '<th class="header c'.$index.$this->column_class[$column].'" scope="col">&nbsp;</th>';

            } else if (!empty($this->sess->collapse[$column])) {
                $code .= '<th class="header c'.$index.$this->column_class[$column].'" scope="col">'.$icon_hide.'</th>';

            } else {

                // took out nowrap for accessibility, might need replacement
                if (!is_array($this->column_style[$column])) {
                    // $usestyles = array('white-space:nowrap');
                    $usestyles = '';
                } else {
                    // $usestyles = $this->column_style[$column]+array('white-space'=>'nowrap');
                    $usestyles = $this->column_style[$column];
                }
                $code .= '<th class="header c'.$index.$this->column_class[$column].'" '
                       .$this->make_styles_string($usestyles).' scope="col">'.$this->headers[$index]
                       .$icon_sort.'<div class="commands">'.$icon_hide.'</div></th>';
            }

        }
        $code .= '</tr>';

        if (!empty($this->data)) {
            $oddeven = 1;
            $colbyindex = array_flip($this->columns);

            foreach ($this->data as $row) {
                $oddeven = $oddeven ? 0 : 1;
                $code .= '<tr class="r'.$oddeven.'">';

                // If we have a separator, print it
                if ($row === null && $colcount) {
                    $code .= '<td colspan="'.$colcount.'"><div class="tabledivider"></div></td>';
                } else {

                    // Antoni Mas
                    foreach ($row->data as $index => $data) {

                        if ($index >= $colcount) {
                            break;
                        }
                        $column = $colbyindex[$index];
                        $code .= '<td class="cell c'.$index.$this->column_class[$column].'"'
                               .$this->make_styles_string($this->column_style[$column]).' '
                               .$this->make_attributes_string($row->attributes).' >';

                        if (empty($this->sess->collapse[$column])) {
                            $suppressed = ($suppress_lastrow !== null && $suppress_lastrow[$index] === $data);

                            if ($this->column_suppress[$column] && $suppressed) {
                                $code .= '&nbsp;';
                            } else {
                                $code .= $data;
                            }
                        } else {
                            $code .= '&nbsp;';
                        }
                        $code .= '</td>';
                    }
                }
                $code .= '</tr>';

                if ($suppress_enabled) {
                    $suppress_lastrow = $row;
                }
            }
        }

        // Antoni Mas. select all/none
        if ($this->input) {
            $all   = '<a href="javascript:void(0);" onclick="select_all(document.sendmail.mail, true);">'
                   .get_string('all') . '</a>';
            $none  = '<a href="javascript:void(0);" onclick="select_all(document.sendmail.mail, false);">'
                   .get_string('none') . '</a>';
            $code .= '<tr><td colspan="'.$colcount.'">'. $all .' / '. $none .'</td></tr>';
        }

        $code .= '</table>';

        // Paging bar
        if ($this->use_pages) {
            $pagingbar = new paging_bar($this->totalrows, $this->currpage, $this->pagesize,
                                        $this->baseurl, $this->request[TABLE_VAR_PAGE]);
            $code .= $OUTPUT->render($pagingbar);
        } else {
            $code .= '</div>';
        }

        if ($addslashes) {
            $code = addslashes($code);
        }
        return $code;
    }

    /**
     * Add some data
     *
     * @param array $row        The data row
     * @param array $attributes The attributes of the data row
     * @return boolean Sometimes returns false.
     */
    function add_data($row, $attributes = null) {

        if (!$this->setup) {
            return false;
        }
        $data = new stdClass;
        $data->data = $row;
        $data->attributes = $attributes;
        $this->data[] = $data;
    }

    /**
     * Add a separator
     *
     * @return boolean Sometimes returns false.
     */
    function add_separator() {

        if (!$this->setup) {
            return false;
        }
        $this->data[] = null;
    }

}
